package com.hackcloud.shardingjdbc.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 模板的读取类
 *
 * @author Jiaju Zhuang
 */
@Slf4j
public class DocReadListener extends AnalysisEventListener<DocData> {
    private static final List<String> DOC_NODE = Arrays.asList("request", "response", "extInfo", "fileExtInfo");
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 200;
    private List<DocData> cachedDataList = new ArrayList<>(BATCH_COUNT);

    @Override
    public void invoke(DocData data, AnalysisContext context) {
        String fileName = context.readWorkbookHolder().getFile().getName();
        String fileNamePrefix = fileName.substring(0, fileName.indexOf("."));
        //String[] split = fileNamePrefix.split("-");
        data.setProductNo(fileNamePrefix);
        //data.setParamType(split[1]);
        data.setScene(context.readSheetHolder().getSheetName());

        if (StringUtils.isEmpty(data.getFieldSortNo())) {
            return;
        }
        cachedDataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        cachedDataList.forEach(x -> {
                    formatData(cachedDataList, x);
                }
        );
        log.info("数据信息{}", cachedDataList);
    }

    /**
     * 扁平化数据
     *
     * @param list
     * @param data
     */
    private void formatData(List<DocData> list, DocData data) {
        int indexOf = data.getFieldSortNo().lastIndexOf(".");
        if (indexOf > -1) {
            String parentSort = data.getFieldSortNo().substring(0, indexOf);
            DocData parentData = list.stream().filter(x -> x.getFieldSortNo().equals(parentSort)).findAny().orElse(null);
            data.setFieldCode(parentData.getFieldCode() + "." + data.getFieldCode());
            data.setParentFieldCode(parentData.getFieldCode());
            data.setParentFieldSortNo(parentData.getFieldSortNo());
        }
    }

    public static void main(String[] args) {
        String no = "2";
        int indexOf = no.lastIndexOf(".");
        System.out.println(indexOf);
    }
}
